const { series, src, dest, watch } = require('gulp');
const fs = require('fs');
const package = require('./package.json');
const { exec } = require('child_process');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');

const build = () =>
  src('src/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(
      babel({
        presets: ['@babel/preset-env'],
        plugins: ['source-map-support', '@babel/plugin-transform-runtime']
      })
    )
    .pipe(
      sourcemaps.write('.', {
        sourceRoot: '../src'
      })
    )
    .pipe(dest('lib'));

const copy = () => src('src/**/*.ejs').pipe(dest('lib'));

const ver = (cb) => {
  // eslint-disable-next-line global-require
  const versionType = package.version.split('.')[0];
  const nowMinorCode = package.version.split('.')[1];
  const { exec } = require('child_process');
  exec(`npm view ${package.name} versions`, (err, stdout) => {
    if (err) {
      return cb(err);
    }
    // console.log(stdout)
    let versions = JSON.parse(stdout.replace(/'/g, '"'));
    console.log('new version:', versions);
    // eslint-disable-next-line radix
    versions = versions.filter(
      (version) => version.split('.')[0] === versionType && version.split('.')[1] === nowMinorCode
    );
    console.log(versions);
    let vers = [versionType, nowMinorCode, 0];
    if (versions.length > 0) {
      // eslint-disable-next-line radix
      vers = versions[versions.length - 1].split('.').map((v) => parseInt(v));
      vers[vers.length - 1] += 1;
    }
    console.log('new version:', vers.join('.'));
    package.version = vers.join('.');
    fs.writeFileSync('./package.json', JSON.stringify(package, null, 2));
    cb();
  });
};

exports.build = series(build, copy);
exports.pub = series(ver, build, copy);
exports.watch = () => watch(['src/**/*'], series(build, copy));
exports.ver = series(ver);
